package com.lz.frame.filter;

import com.google.gson.Gson;
import com.lz.frame.common.R;
import com.lz.frame.config.security.MyUserDetails02;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.Map;

@RestControllerAdvice
public class TraceIdResponseAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String traceId = (String) request.getAttribute("traceId");
        if (obj instanceof R) {
            R<?> r = (R<?>) obj;
            r.addTraceIdAndTime(traceId, new Date());
            return r;
        } else if (obj instanceof Map) {
            Map map = (Map) obj;
            map.put("traceId", traceId);
            return map;
        }
        return obj;
    }



}